<?php
/*
 * Created on 22 mai 2011
 * By Guillaume Dugas
 * 
 */

class DatabaseConditions {
	
	// Données clauses WHERE
	private $cndReq		= "";
	private $groupConn	= array('AND');
	private $groupStack	= 0;
	
	private $orders		= array();
	
	function __construct() {
		// Initialisation des groupes des conditions
	}
	
	/*
	 * bool add( string $col, string $op, string $value)
	 *  Ajoute une clause WHERE au groupe définie par $this->startGroup($group)
	 *  
	 *  valeurs de retour:
	 *  	True si ok, False sinon (operateur non valide ou groupe inexistant)
	 */
	 function add($col,$op,$value) {
		switch(trim(strtoupper($op))) {
			case '=':
			case '<>':
			case '>':
			case '>=':
			case '<':
			case '<=':
			case 'LIKE':
			case 'BETWEEN':
				$this->cndReq .= $col . $op ."'". $value ."' ".$this->groupConn[$this->groupStack]." ";
				return True;
				break;
			
			default:
				return False;
				break;
		}
	}
	
	
	function endGroup() {
		if( $this->groupStack == 0 )
			return False;
		
		$this->cndReq = substr( $this->cndReq, 0, strlen($this->cndReq) - strlen($this->groupConn[$this->groupStack]) - 1 );
		$this->groupStack --;
		$this->cndReq .= ") ".$this->groupConn[$this->groupStack]. " ";
		return True;
	}
	

	function getConditions() {
		$req	= $this->cndReq;
		$groups	= $this->groupConn;
		$stack	= $this->groupStack;
		while( $stack > 0) {
			$req	= substr( $req, 0, strlen($req) - strlen($groups[$stack]) - 1 );
			$stack --;
			$req .= ") ".$groups[$stack]. " ";
		}
		$req = substr($req, 0, strlen($req) - strlen($groups[$stack]) - 1);
		return $req;
	}
	
	
	function getOrders() {
		if( count($this->orders) == 0)
			return "";
		else
			return implode(', ',$this->orders);
	}
	
	function order( $col, $order = 'asc' ) {
		$order = strtolower($order);
		
		if( $order != 'asc' && $order != 'desc' )
			return false;
		
		array_push( $this->orders, $col . " " . $order );
		return True;
	}
	
	
	function startGroup($conn) {
		$conn = trim(strtoupper($conn));
		
		if( $conn == 'OR' || $conn == 'AND') {
			array_push( $this->groupConn, $conn );
			$this->cndReq	.= "( ";
			$this->groupStack ++;
			return True;
		} else {
			return False;
		}
	}
	
}